<template>
  <div>
    <el-dialog @close="cancel" destroy-on-close v-model="DialogVisible" :title="namstr" align-center @opened="onDrawerOpened">
      <div style="height: 50vh; overflow: scroll">
        <el-form
          style="height: 100%"
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
        >
          <el-row :gutter="30">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="用户代码" prop="struCode">
                <!-- namstr=='' disabled -->
                <el-input v-model="ruleForm.struCode" ref="adduserjd" @keydown.enter="adduserjdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="用户名称" prop="struName">
                <el-input v-model="ruleForm.struName" ref="struNamejd" @keydown.enter="struNamejdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="身份证号" prop="strShenFenZhengHao">
                <el-input
                  v-model="ruleForm.strShenFenZhengHao"
                  ref="strShenFenZhengHaojd"
                  @keydown.enter="strShenFenZhengHaoDown"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="拼音码" prop="struPYM">
                <el-input v-model="ruleForm.struPYM" disabled ref="struPYM" @keydown.enter="struPYMDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="职业类别" prop="strZhiYeLeiBie">
                <el-input v-model="ruleForm.strZhiYeLeiBie" ref="strZhiYeLeiBiejd" @keydown.enter="strZhiYeLeiBiejdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="药师职称" prop="strYaoShiZhiCheng">
                <el-input
                  v-model="ruleForm.strYaoShiZhiCheng"
                  ref="strYaoShiZhiChengjd"
                  @keydown.enter="strYaoShiZhiChengjdDown"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="所属科室" prop="strSuoShuKeShi">
                <el-input v-model="ruleForm.strSuoShuKeShi" ref="strSuoShuKeShijd" @keydown.enter="strSuoShuKeShijdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="学历" prop="strXueLi">
                <el-input v-model="ruleForm.strXueLi" ref="strXueLijd" @keydown.enter="strXueLijdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="手机号码" prop="strShouJiHao">
                <el-input v-model="ruleForm.strShouJiHao" ref="strShouJiHaojd" @keydown.enter="strShouJiHaojdDown" />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="是否总检医师" prop="strShiFouZongJianYiShi">
                <el-select
                  v-model="ruleForm.strShiFouZongJianYiShi"
                  class="m-2"
                  ref="strShiFouZongJianYiShijd"
                  @keydown.enter="strShiFouZongJianYiShijdDown"
                >
                  <el-option v-for="item in shifou" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="用户最大折扣" prop="strYongHuZuiDaZheKou">
                <el-input
                  ref="strYongHuZaiDaZheKoujd"
                  @keydown.enter="strYongHuZaiDaZheKoujdDown"
                  v-model="ruleForm.strYongHuZuiDaZheKou"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="备注" prop="strBeiZhu">
                <el-input v-model="ruleForm.strBeiZhu" ref="strBeiZhu" type="textarea" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="电子签名" prop="name">
                <upload ref="uploads" :imgurl="imgurl" :port="port" @uploadsuccess="uploadsuccess"></upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect, reactive } from "vue";
import type { FormInstance } from "element-plus";
import upload from "@/components/Upload/index.vue";
import { PostUserAddport, PutUserUpdateport } from "@/api/modules/user";
import { ElMessage } from "element-plus";
import { pinyin } from "pinyin-pro";
import { useFocusInput } from "@/utils";
const shifou = [
  { value: "否", label: "否" },
  { value: "是", label: "是" }
];
const imgurl = ref<string>("");
const uploads = ref();
const port = "http://120.55.65.152:4001/api/File/v1.0/FileUpload?filePath=DianZiQianMing";
const namstr = ref<string>("");
const DialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<any>({
  strUserId: "",
  strJueSeId: "",
  struCode: "",
  struName: "",
  struPYM: "",
  strShenFenZhengHao: "",
  strZhiYeLeiBie: "",
  strYaoShiZhiCheng: "",
  strSuoShuKeShi: "",
  strXueLi: "",
  strShouJiHao: "",
  strBeiZhu: "",
  strShiFouZongJianYiShi: "否",
  strDianZiQianMing: "",
  strYongHuZuiDaZheKou: ""
});
const edittapevalue = ref<any>(null);
// 正则
const rules = reactive<any>({
  struCode: [
    { required: true, message: "不可为空", trigger: "blur" },
    { pattern: /\S/, message: "不可只输入空格", trigger: "blur" }
  ],
  struName: [
    { required: true, message: "不可为空", trigger: "blur" },
    { pattern: /\S/, message: "不可只输入空格", trigger: "blur" },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: "只能输入中文", trigger: "blur" }
  ],
  strShouJiHao: [{ pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }],
  strShenFenZhengHao: [{ pattern: /(^\d{15}$)|(^\d{17}(\d|X|x)$)/, message: "身份证号格式不正确", trigger: "blur" }]
});

const uploadsuccess = (img: any) => {
  ruleForm.strDianZiQianMing = img ? img : "";
};

const clear = () => {
  imgurl.value = "";
  namstr.value == "新增用户";
  edittapevalue.value = null;
  Object.keys(ruleForm).forEach((key: any) => {
    if (key === "strShiFouZongJianYiShi") {
      ruleForm[key] = "否";
    } else {
      ruleForm[key] = "";
    }
  });
};

// 确定
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (namstr.value == "新增用户") {
        if (ruleForm.struPYM == "") {
          const firstChars = ruleForm.struName
            .split("")
            .map(char => pinyin(char, { style: pinyin.STYLE_NORMAL })[0])
            .join("")
            .replace(/[^a-zA-Z]/g, ""); // 使用正则表达式去除非字母字符

          const result = firstChars.toUpperCase(); // 转换为大写
          ruleForm.struPYM = result;
        }
        PostUserAddport(ruleForm).then((res: any) => {
          console.log(res);
          if (res.Success == 0) {
            ElMessage.success("添加成功");
            emit("succeedwin");
            emit("distancecancel", false);
            uploads.value.image = "";
            clear();
          } else {
            emit("distancecancel", false);
            uploads.value.image = "";
            clear();
          }
        });
      } else if (namstr.value == "编辑用户") {
        console.log(ruleForm, "ruleFormruleFormruleFormruleFormruleFormruleFormruleForm");
        const firstChars = ruleForm.struName.split("").map(char => pinyin(char, { style: pinyin.STYLE_FIRST_LETTER })[0]);
        const result = firstChars.join("");
        ruleForm.struPYM = result;
        PutUserUpdateport(ruleForm).then((res: any) => {
          console.log(res);
          if (res.Success == 0) {
            ElMessage.success("修改成功");
            emit("succeedwin");
            emit("distancecancel", false);
            uploads.value.image = "";
            clear();
          } else {
            emit("distancecancel", false);
            uploads.value.image = "";
            clear();
          }
        });
      }

      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

// const onDrawerOpened = () => {
//   adduserjd.focus();
// };

// 接收父组件传来的数据
const props = defineProps({
  addusershow: {
    type: Boolean,
    default: () => false
  },
  adduser: {
    type: String,
    default: () => "新增用户"
  },
  jueseid: {
    type: String,
    default: () => ""
  },
  edittapevalues: {
    type: Object,
    default: () => null
  }
});

const emit = defineEmits(["distancecancel", "succeedwin"]);
// 取消
const cancel = () => {
  clear();
  emit("distancecancel", false);
  console.log(ruleForm);
};

const ex = () => {
  console.log(uploads.value);
  if (uploads.value == undefined) {
    return;
  } else {
    uploads.value.image = "";
  }
};

defineExpose({
  edittapevalue,
  imgurl,
  ex
});

watchEffect(() => {
  DialogVisible.value = props.addusershow;
  namstr.value = props.adduser;
  ruleForm.strJueSeId = props.jueseid;
  edittapevalue.value = props.edittapevalues;
  console.log(edittapevalue.value);

  if (namstr.value == "编辑用户") {
    ruleForm.strUserId = edittapevalue.value.UserID;
    ruleForm.strJueSeId = edittapevalue.value.JueSeID;
    ruleForm.struCode = edittapevalue.value.uCode;
    ruleForm.struName = edittapevalue.value.uName;
    ruleForm.struPYM = edittapevalue.value.uPY;
    ruleForm.strShenFenZhengHao = edittapevalue.value.ShenFenZhengHao;
    ruleForm.strZhiYeLeiBie = edittapevalue.value.ZhiYeLeiBie;
    ruleForm.strYaoShiZhiCheng = edittapevalue.value.YaoShiZhiCheng;
    ruleForm.strSuoShuKeShi = edittapevalue.value.SuoShuKeShi;
    ruleForm.strXueLi = edittapevalue.value.XueLi;
    ruleForm.strShouJiHao = edittapevalue.value.ShouJiHao;
    ruleForm.strBeiZhu = edittapevalue.value.BeiZhu;
    ruleForm.strShiFouZongJianYiShi = edittapevalue.value.ShiFouZongJianYiShi;
    ruleForm.strDianZiQianMing = edittapevalue.value.DianZiQianMing;
    ruleForm.strYongHuZuiDaZheKou = edittapevalue.value.YongHuZuiDaZheKou;
    imgurl.value = edittapevalue.value.DianZiQianMing;
    console.log(ruleForm);
  } else if (namstr.value == "新增用户") {
    clear();
    ruleForm.strJueSeId = props.jueseid;
  }
});
const [adduserjd, onDrawerOpened] = useFocusInput();
const [struNamejd, adduserjdDown] = useFocusInput();
const [strShenFenZhengHaojd, struNamejdDown] = useFocusInput();
const [struPYM, strShenFenZhengHaoDown] = useFocusInput();
const [strZhiYeLeiBiejd, struPYMDown] = useFocusInput();
const [strYaoShiZhiChengjd, strZhiYeLeiBiejdDown] = useFocusInput();
const [strSuoShuKeShijd, strYaoShiZhiChengjdDown] = useFocusInput();
const [strXueLijd, strSuoShuKeShijdDown] = useFocusInput();
const [strShouJiHaojd, strXueLijdDown] = useFocusInput();
const [strShiFouZongJianYiShijd, strShouJiHaojdDown] = useFocusInput();
const [strYongHuZaiDaZheKoujd, strShiFouZongJianYiShijdDown] = useFocusInput();
const [strBeiZhu, strYongHuZaiDaZheKoujdDown] = useFocusInput();
</script>

<style scoped>
:deep .el-form-item {
  margin-bottom: 0;
}
</style>
